package com.paranoid.flashcard.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.paranoid.flashcard.R;
import com.paranoid.flashcard.dao.FlashcardDao;
import com.paranoid.flashcard.dao.FlashcardDatabase;
import com.paranoid.flashcard.dao.QuizletDao;
import com.paranoid.flashcard.logic.DownloadService;
import com.paranoid.flashcard.model.Deck;

public class FeaturedActivity extends Activity {
	
	FlashcardDao mFlashcardDao;
	QuizletDao mQuizletDao;
	private SimpleCursorAdapter mAdapter;
	private MyListView mListView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mQuizletDao = QuizletDao.getInstance();
		mFlashcardDao  = FlashcardDao.getInstance(this);
		setContentView(R.layout.fetured);
        Cursor cursor = mQuizletDao.getFeaturedDecks();
        FlashcardDatabase.saveDatabaseToSd();
        mAdapter = new SimpleCursorAdapter(this, R.layout.featured_item, cursor, new String[] {Deck.KEY_TITLE}, new int[] {R.id.contact_name});

        mListView = (MyListView)findViewById(R.id.listView);
		mListView.setAdapter(mAdapter);
		mListView.setDynamics(new SimpleDynamics(0.9f, 0.6f));
        mListView.enableRotation(false);
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DemoPopupWindow dw = new DemoPopupWindow(view, position);
				dw.showLikeQuickAction(0, 30);
			}
			
		});
		
		Button refreshButton = (Button)findViewById(R.id.refresh_button);
		refreshButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FeaturedActivity.this, "refreshing", Toast.LENGTH_SHORT).show();
                Cursor cursor = mQuizletDao.downloadFeaturedDecks();
                mAdapter.changeCursor(cursor);
            }
		});
	}
	
    /**
     * A very simple dynamics implementation with spring-like behavior
     */
    class SimpleDynamics extends Dynamics {

        /** The friction factor */
        private float mFrictionFactor;

        /** The snap to factor */
        private float mSnapToFactor;

        /**
         * Creates a SimpleDynamics object
         * 
         * @param frictionFactor The friction factor. Should be between 0 and 1.
         *            A higher number means a slower dissipating speed.
         * @param snapToFactor The snap to factor. Should be between 0 and 1. A
         *            higher number means a stronger snap.
         */
        public SimpleDynamics(final float frictionFactor, final float snapToFactor) {
            mFrictionFactor = frictionFactor;
            mSnapToFactor = snapToFactor;
        }

        @Override
        protected void onUpdate(final int dt) {
            // update the velocity based on how far we are from the snap point
            mVelocity += getDistanceToLimit() * mSnapToFactor;

            // then update the position based on the current velocity
            mPosition += mVelocity * dt / 1000;

            // and finally, apply some friction to slow it down
            mVelocity *= mFrictionFactor;
        }
    }
	
    
	private class DemoPopupWindow extends BetterPopupWindow implements OnClickListener {
		private int mPosition;
		public DemoPopupWindow(View anchor, int position) {
			super(anchor);
			mPosition = position;
		}

		@Override
		protected void onCreate() {
			// inflate layout
			LayoutInflater inflater =
					(LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			ViewGroup root = (ViewGroup) inflater.inflate(R.layout.import_quickactions_layout, null);
			
			View studyView = root.findViewById(R.id.decklist_preview);
			studyView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					DemoPopupWindow.this.dismiss();
					Toast.makeText(v.getContext(), "Coming soon", Toast.LENGTH_SHORT).show();
				}
				
			});

			View deleteView = root.findViewById(R.id.decklist_download);
			deleteView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					DemoPopupWindow.this.dismiss();
					SimpleCursorAdapter adapter = FeaturedActivity.this.mAdapter;
					Cursor cursor = adapter.getCursor();
					cursor.moveToPosition(mPosition);
					adapter.notifyDataSetChanged();
					
					long id = Deck.getId(cursor);
					String title = Deck.getTitle(cursor);
					
					Log.i("", "Clicked: id=" + id);
					mFlashcardDao.updateDeckStatus(title, id);
					cursor.requery();
					mListView.setAdapter(adapter);
					Intent i = new Intent(FeaturedActivity.this, DownloadService.class);
					i.putExtra("QuizletDeckId", id);
					i.putExtra("QuizletDeckTitle", title);
					FeaturedActivity.this.startService(i);
				}
			});

			// set the inflated view as what we want to display
			this.setContentView(root);
		}

		@Override
		public void onClick(View v) {
			// we'll just display a simple toast on a button click
			Button b = (Button) v;
			Toast.makeText(this.anchor.getContext(), b.getText(), Toast.LENGTH_SHORT).show();
			this.dismiss();
		}
	}
    
	
}
